<template>
  <el-card v-if="show" class="box-card" style="width:100%;height:400px;float:left;text-align:center;margin-top:10px;box-shadow:0 0 45px rgba(0, 0, 0, .3);">
    <div style="text-align:center;margin:10px">
      <i class="fa fa-eye fa-1x" style="color:#1FABB6;margin-right:10px"></i>人脸识别
    </div>
    <video id="video" width="240" height="160"></video>
    <div>
      <el-progress type="circle" :percentage="percentage" :status="status" :width="100"></el-progress>
    </div>
    <div style="margin-top:20px">
      <el-button @click="init" type="warning" plain >录入人脸</el-button>
      <el-button @click="cancelS" type="warning" plain >取消</el-button>
    </div>
    <canvas id="canvas" width="240" height="180" style="display:none"></canvas>


  </el-card>
</template>

<script>
  import CHAT from "../assets/client"
  export default {
    components: {

    },
    data(){
      return {
        lock:true,
        photo:'',
        timer:null,
        CHAT,
        show:false,
        success:null,
        error:null,
        stop:null,
        percentage:0,
        hh:0,
        status:"exception"
      }
    },
    methods: {


      dataURLtoFile(dataurl, filename) {//将base64转换为文件
          var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type:mime});
      },
      cancelS(){
        this.show = false;
        this.stop && this.stop.stop();
        this.$emit("error");
        this.$message('取消校验');
        window.clearInterval(this.timer);
      },
      capture (video,context) {

        if(this.hh==0){

          this.hh=1
          console.log(this.hh)
          if(this.show){
            if(this.lock){


              context.drawImage(video, 0, 0, 240, 180);
              var imgData = canvas.toDataURL();




              var  file=this.dataURLtoFile(imgData, "123.png")


              console.log(file)
              this.lock = false;
              var th =this;


              console.log("111")

              let formData = new FormData();
              console.log("222")
              formData.append("file", file)
              console.log("333")
              console.log(formData)
              console.log("444")




              var _this=this
              axios.post('/upload/singlefile', formData)
                .then(function (response) {
                  alert(response.data);

                  console.log(response);
                 _this.photo= response.data;


                 let id= _this.$route.query.mallCode
                  console.log(id)
                  axios.post('/workroom/upGroupPhoto',{
                    id: id,
                   photo: _this.photo
                  }).then((response) => {
                    if(response.data.states==800){

                      // var e=response.data
                      // console.log(e)

                    }
                    else{
                    }

                  }).catch((response)=>{
                    // this.$notify.error({
                    //   title: '',
                    //   message: '错误'
                    // });
                  })


                })
                .catch(function (error) {
                  alert("上传失败");
                  console.log(error);
                });



            }
          }else{
            window.clearInterval(this.timer);
          }

        }




      },
      getUserMedia(constraints, success, error) {
        if (navigator.mediaDevices.getUserMedia) {
          //最新的标准API
          navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
        } else if (navigator.webkitGetUserMedia) {
          //webkit核心浏览器
          navigator.webkitGetUserMedia(constraints,success, error)
        } else if (navigator.mozGetUserMedia) {
          //firfox浏览器
          navigator.mozGetUserMedia(constraints, success, error);
        } else if (navigator.getUserMedia) {
          //旧版API
          navigator.getUserMedia(constraints, success, error);
        }
      },
      init(){
        console.log("aaaaaa")
        var th = this;
        let video = document.getElementById('video');
        let canvas = document.getElementById('canvas');
        let context = canvas.getContext('2d');

        function success(stream) {
          //兼容webkit核心浏览器
          console.log("bbb")
          let CompatibleURL = window.URL || window.webkitURL;
          //将视频流设置为video元素的源
          console.log(stream);
          //video.src = CompatibleURL.createObjectURL(stream);
          video.srcObject = stream;
          video.play();


          th.mediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[1];
          th.stop = stream.getTracks()[0];
        }

        function error(error) {
          console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
        }

        if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
          //调用用户媒体设备, 访问摄像头
          this.getUserMedia({video : {width: 240, height: 160}}, success, error);
        } else {
          alert('不支持访问用户媒体');
        }

        this.timer = setInterval(()=>{
          this.capture(video,context)
        },1500);

      }
    },
    created() {

    },
    mounted () {
      this.show = true;
      this.lock = true;
      this.percentage = 0;
      // this.$nextTick(() => {
      //   this.init();
      // })
    },
    beforeDestroy(){},
  }
</script>

<style>

</style>
